<template>
  <div class="container">
    <Title title="收款账户" style="margin-bottom: 12px;" />
    <div class="account-list scroll">
      <div v-for="(settingItem, index) in listSetting" :key="index" class="account-item">
        <div class="label">
          <span v-if="isEdit" class="is-require">*</span>
          {{ settingItem.label }}
          <InfoIcon v-if="isEdit && settingItem.keyword === 'bank'" content="输入系统中未添加的银行名称时将自动添加该银行" style="margin-left: 4px;" />
        </div>
        <div v-if="isEdit" :class="{'isError': errorIds.includes(settingItem.keyword)}" class="edit-value">
          <el-input
            v-if="settingItem.type === 'inputText'"
            v-model="collectAccount[settingItem.keyword]"
            :maxlength="50"
            :placeholder="settingItem.placeholder"
            size="small"
            type="text"
            class="edit-table-input-text"
            clearable
            @change="changeValue"
          />
          <!-- 输入框：带输入建议 autocomplete -->
          <el-autocomplete
            v-if="settingItem.type === 'autocomplete'"
            v-model="collectAccount[settingItem.keyword]"
            :maxlength="50"
            :fetch-suggestions="(queryString, cb) => {fetchAutocomplete(queryString, cb, settingItem)}"
            placeholder="请输入内容"
            size="small"
            @change="changeValue"
            @select="autocompleteSelect($event, settingItem)"
          />
          <!-- 下拉选项 -->
          <selectWithoutHttp
            v-if="settingItem.type === 'select'"
            v-model="collectAccount[settingItem.keyword]"
            :list-data="settingItem.options || []"
            :multiple="false"
            :disabled="settingItem.disabled"
            :key-name="settingItem.keyName ? settingItem.keyName : 'id'"
            :label-name="settingItem.labelName ? settingItem.labelName : 'name'"
            :allow-create="settingItem.allowCreate"
            :create-new="settingItem.createNew"
            filterable
            clearable
            @change="changeValue"
            @createNewItem="addNewBank"
          />
          <!-- 城市级联选择 -->
          <three-level-area
            v-if="settingItem.type === 'selectCity'"
            :select-type="settingItem.selectType || 'region'"
            :placeholder="settingItem.placeholder"
            :separator="settingItem.separator"
            :selected-options="handelArr(collectAccount[settingItem.keyword])"
            @update:options="threeLevelArea($event, collectAccount, settingItem.keyword)" />
        </div>
        <div v-else class="show-value">
          <SecretText
            v-if="settingItem.showType==='secret'"
            :log-text="setLogText(collectAccount)"
            :origin-text="collectAccount[settingItem.keyword]" />
          <ToolTip v-else :content="collectAccount[settingItem.keyword]" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Title from '@/components/Title';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';

import { accountList } from '@/api/supplier';
import { collectionAccount1, collectionAccount2 } from './data';
// mixins
import accountTable from '@/mixins/accountTable';
export default {
  name: 'CollectAccount',
  components: { Title, ThreeLevelArea, selectWithoutHttp },
  mixins: [accountTable],
  model: {
    prop: 'collectAccount',
    event: 'changeValue'
  },
  props: {
    collectAccount: {
      type: Object,
      default: () => ({
        bank: '',
        payName: '',
        payNum: '',
        province: '',
        subBank: ''
      })
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    supplierId: {
      type: Number | String,
      default: null
    },
    costBelong: {
      type: Number,
      default: 0
    },
    isCommerce: { // 是否为有赞供应商
      type: Boolean,
      default: false
    },
    accountType: { // 2 对公银行账户， 3 对公其他账户
      type: Number,
      default: null
    },
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    widthdrawInfo: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      errorIds: []
    };
  },
  computed: {
    listSetting() {
      const list = this.accountType === 2 ? collectionAccount1 : collectionAccount2;
      list.forEach(i => {
        if (i.keyword === 'bank') i.options = this.bankList;
        if (i.keyword === 'payPlatform') i.options = this.paymentList;

        if (this.stepOneData.process === 4 || [3, 4].includes(this.widthdrawInfo.examineStatus)) {
        // 审批完成或者已撤销收款账号加密
        // examineStatus，是单个审批单的审批状态 3:已作废 4:审批完成
          if (i.keyword === 'payNum') {
            i.showType = 'secret';
          }
        }
      });
      return list;
    }
  },
  created() {
    this.getBankList();// 获取银行名称列表
    this.getPaymentList();
    if (this.isEdit) this.fillFirstAcount();
  },
  methods: {
    validate() {
      return new Promise((resolve, reject) => {
        const key = this.listSetting.map(it => it.keyword);
        for (const i of key) {
          if (!this.collectAccount[i] && this.collectAccount[i] !== 0 && !this.errorIds.includes(i)) {
            this.errorIds.push(i);
          }
        }
        if (this.errorIds.length > 0) {
          reject(false);
        } else {
          resolve(true);
        }
      });
    },
    backfillBank(name) {
      this.collectAccount.bank = name;
    },
    clearValidate() {
      this.errorIds = [];
    },
    fetchAutocomplete(value, cb, settingItem) {
      if (settingItem.keyword === 'payName') {
        // costBelong  0:渠道订单 1:项目订单 2:商务订单 3:营销授权 5:项目渠道单
        let type = (this.costBelong === 2 || this.costBelong === 3) ? 2 : 1;
        if (this.isCommerce) { // 如果是有赞
          type = 3;
        }
        const params = {
          page: 1,
          perPage: 100,
          type: type,
          id: this.supplierId,
          supplierId: this.supplierId
        };
        if (value) params.payName = value;
        accountList(params).then(res => {
          if (res.code === 200) {
            res.data.items.forEach(i => {
              const str = i.payNum.slice(-4);
              i.value = i.payPlatform ? `${i.payPlatform}， ${i.payName}(${str})` : `${i.payName}(${str})`;
            });
            cb(res.data.items);
          } else {
            cb([]);
          }
        }).catch(() => {
          cb([]);
        });
      }
    },
    autocompleteSelect(value, settingItem) {
      if (settingItem.keyword === 'payName') {
        const selectItem = _.cloneDeep(value);
        const key = this.listSetting.map(it => it.keyword);
        for (const i of key) {
          if (i === 'province' && selectItem[i]) {
            selectItem[i] = selectItem[i].replace('-', ',');
          }
          this.$set(this.collectAccount, i, selectItem[i]);
        }
        this.$forceUpdate();
        this.$nextTick(() => {
          this.changeValue();
        });
      }
    },
    // 自动填充 默认获取该供应商账户列表创建时间最近的收款账号信息
    fillFirstAcount() {
      // 只有当收款人列表为空时才填充
      const item = this.collectAccount;
      if (this.supplierId && this.collectAccount && !item.payName && !item.payNum) {
        const type = (this.costBelong === 2 || this.costBelong === 3) ? 2 : 1;
        const params = {
          page: 1,
          perPage: 100,
          type: type,
          id: this.supplierId,
          supplierId: this.supplierId
        };
        accountList(params).then(res => {
          if (res.data && res.data.items.length) {
            const settingItem = { keyword: 'payName' };
            this.autocompleteSelect(res.data.items[0], settingItem);
          }
        });
      }
    },
    // 选择城市
    threeLevelArea(data, item, key) {
      item[key] = data.join(',');
      this.changeValue();
    },
    handelArr(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.split(',');
      } else {
        return data;
      }
    },
    changeValue() {
      this.errorIds = [];
      this.$emit('changeValue', this.collectAccount);
    },
    setLogText(item) {
      return `付款申请${this.widthdrawInfo.settleName}的收款信息${item.payName}的收款账号`;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  margin-top: 30px;
}
.account-list {
  display: flex;
}
.account-item {
  border-right: 1px solid #EBEEF5;
  border-bottom: 1px solid #EBEEF5;
  flex: 1;
  min-width: 100px;
  .label {
    display: flex;
    padding: 0 10px;
    align-items: center;
    background: #F9F9F9;
    font-size: 14px;
    color: #141C3D;
    font-weight: 600;
    height: 38px;
    border-bottom:  1px solid #EBEEF5;
    .is-require {
      color: #f56c6c;
      margin-right:4px;
    }
  }
  .show-value {
    color: #333;
    font-size: 14px;
    padding: 12px 10px;
  }
  .edit-value {
    &::v-deep {
      .el-select {
        width: 100%;
      }
      .threee-level-area-wrap {
        .el-cascader {
          width: 100% !important;
        }
        .el-input {
          display: flex;
        }
        .el-input__inner{
          width: 100%;
        }
      }
      .el-autocomplete {
          width: 100%;
      }
      .el-input__inner {
        height: 56px;
        border-radius: 0;
        border-color: transparent;
      }
    }
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: red !important;
    }
  }
}
.scroll {
  @include scrollBar($x: auto, $y: hidden);
}
</style>
